<template>
  <div>
    <canvas ref="canvasRef"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { fabric } from 'fabric';

const canvasRef = ref(null);
let canvas = null;

onMounted(() => {
  // 初始化 Fabric.js 画布
  canvas = new fabric.Canvas(canvasRef.value, {
    backgroundColor: 'lightgray',
    width: 800,
    height: 600,
  });

  // 加载本地图片
  fabric.Image.fromURL('/assets/logo.png', (img) => {
    img.set({
      left: 50,
      top: 50,
      scaleX: 0.5,
      scaleY: 0.5,
      hasControls: true, // 允许缩放和旋转
      selectable: true,
    });

    canvas.add(img);
    canvas.setActiveObject(img);
    canvas.renderAll();
  });

  // 监听手指事件
  const handleTouch = (event) => {
    const touch = event.touches[0];
    if (touch) {
      const rect = canvasRef.value.getBoundingClientRect();
      const pointer = canvas.getPointer({
        clientX: touch.clientX - rect.left,
        clientY: touch.clientY - rect.top,
      });

      // 触摸移动图片
      const activeObject = canvas.getActiveObject();
      if (activeObject) {
        activeObject.set({ left: pointer.x, top: pointer.y });
        canvas.renderAll();
      }
    }
  };

  // 监听事件
  canvasRef.value.addEventListener('touchmove', handleTouch);

  // 组件销毁时清理
  onUnmounted(() => {
    canvasRef.value?.removeEventListener('touchmove', handleTouch);
    canvas.dispose();
  });
});
</script>

<style scoped>
canvas {
  border: 1px solid #ccc;
  touch-action: none; /* 禁止默认滚动，防止冲突 */
}
</style>
